import 'package:bot_toast/bot_toast.dart';
import 'package:cave_flutter/config/whl_base_controller.dart';
import 'package:cave_flutter/network/whl_api.dart';
import 'package:cave_flutter/pages/whl_login/view/whl_login_agreement_dialog.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';

import '../../../common/common_action.dart';
import '../../../network/whl_network_utils.dart';
import '../../../routes/whl_app_pages.dart';
import '../../../utils/whl_toast_utils.dart';
import '../login_for_phone/login_for_phone_logic.dart';

class LoginForPasswordLogic extends WhlBaseController {
  TextEditingController phoneController = TextEditingController();
  TextEditingController passwordController = TextEditingController();
  bool agreePrivateStatus = false;

  bool isBtnEnable = false;

  onCheckBtnEnable() {
    if (phoneController.text.length == 11 && passwordController.text.length >= 6) {
      isBtnEnable = true;
    } else {
      isBtnEnable = false;
    }
    update();
  }

  doClickLoginForPhone() {
    if (Get.isRegistered<LoginForPhoneLogic>()) {
      Get.until((route) => route.settings.name == Routes.loginForPhone);
    } else {
      Get.offNamed(Routes.loginForPhone);
    }
  }

  doClickSelect() {
    agreePrivateStatus = !agreePrivateStatus;
    update();
  }

  doClickLogin() {
    if (!agreePrivateStatus) {
      Get.dialog(WhlLoginAgreementDialog(onTagAgree: () {
        agreePrivateStatus = true;
        update();
        onLogin();
      }));
    } else {
      onLogin();
    }
  }

  onLogin() {
    if (phoneController.text.isEmpty) {
      MyToast.show('请输入手机号');
      return;
    }
    if (phoneController.text.length != 11) {
      MyToast.show('请输入正确的手机号');
      return;
    }
    if (passwordController.text.isEmpty) {
      MyToast.show('请输入密码');
      return;
    }
    BotToast.showLoading();
    WhlApi.passwordLogin.post({
      "password": passwordController.text,
      "phone": phoneController.text,
    }).then((value) {
      if (value.isSuccess()) {
        Map dic = value.data;
        String token = dic["token"];
        WhlNetWorkUtils.setAccessToken(token);
        // Get.offNamed(Routes.main);
        getUserInfo(isLogin: true,callback: (isSuccess){
          BotToast.closeAllLoading();
          if (!isSuccess) {
            MyToast.show("获取用户信息失败");
          }
        });
      }else {
        BotToast.closeAllLoading();
      }
    });

  }
}
